package com.z.utils;

import java.util.Calendar;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class CommonUtil {
	
	/**
	 * 将null转换为空字符串
	 * @param str
	 * @return
	 */
	public static String formatNullToEmpty(Object str) {
		return str == null ? "" : str.toString();
	}
	
	/**
	 * 获取员工工龄
	 * @param joinTime 员工入职日期的字符串形式可以是年如2013，也可以是年月如201309
	 * @return 返回年工工龄，不满一年视为一年
	 */
	public static int getWorkAge(String joinTime) {
		try {
			if (joinTime.length() > 4) {
				joinTime = joinTime.substring(0, 4);
			}
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(calendar.YEAR);
			int joinYear = Integer.valueOf(joinTime);
			int res = year - joinYear;
			return res > 0 ? res : 1;
		} catch (Exception e) {
		}
		return 1;
	}
	
	/**
	 * 生成指定长度的数字字符串
	 * @param len 指定长度
	 * @return
	 */
	public static String getRadomNumberStr(int len) {
		StringBuffer sbr = new StringBuffer();
		Random r = new Random();
		for (int i = 0; i < len; i++) {
			sbr.append(r.nextInt(10));
		}
		return sbr.toString();
	}
	
	/**
	 * 整数自动加一,当数字等于最大数字时返回0
	 * @param num 当前数字
	 * @param limit 最大限制
	 * @return
	 */
	public static int numAdd1Limit(int num, int limit) {
		num++;
		if (num >= limit) {
			num = 0;
		}
		return num;
	}
	
	/**
	 * 数字格式化为字符
	 * @param num 数字
	 * @param minLength 最小长度，不足时前面补0
	 * @return
	 */
	public static String numberToString(int num, int minLength) {
		try {
			String res = String.valueOf(num);
			int dis = minLength - res.length();
			if (dis > 0) {
				StringBuffer sbr = new StringBuffer();
				for(int i = 0; i < dis; i++) {
					sbr.append("0");
				}
				sbr.append(res);
				return sbr.toString();
			} else {
				return res;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 根据值获取键
	 * @param map map集合
	 * @param value 指定值
	 * @return
	 */
	public static String getMapKeyByFirstValue(Map<String, String> map, String value) {
		if (value != null && map != null) {
			Set<String> setList = map.keySet();
			for (String key : setList) {
				if (value.equals(map.get(key))) {
					return key;
				}
			}
		}
		return null;
	}
}
